import router, { asyncRoutes, constantRoutes } from '@/router';
import { getMenus } from '@/api/user';
import Layout from '@/layout';

function matchComponent(path) {
  for (let j = 0; j < asyncRoutes.length; j++) {
    if (asyncRoutes[j].path === path) {
      return asyncRoutes[j].component;
    }
    // 有子路由
    if (asyncRoutes[j].children && asyncRoutes[j].children.length > 0) {
      const childrenRoutes = asyncRoutes[j].children;
      for (let i = 0; i < childrenRoutes.length; i++) {
        const subItem = childrenRoutes[i];
        if (subItem.path === path) {
          return subItem.component;
        }
      }
    }
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes routes
 */
function filterAsyncRoutes(routes) {
  const res = [];
  routes.forEach(route => {
    if (route.parentId === '0' && route.children.length === 0) {
      route.component = matchComponent(route.path);
      const tempRoute = {
        path: route.path,
        component: Layout,
        children: [
          {
            path: route.path,
            component: matchComponent(route.path),
            name: route.name,
            meta: route.meta
          }
        ]
      };
      res.push(tempRoute);
      return;
    }
    if (route.component === 'Layout') {
      route.component = Layout;
    } else {
      // 匹配组件
      route.component = matchComponent(route.path);
    }
    if (route.children && route.children.length > 0) {
      filterAsyncRoutes(route.children);
    }
    res.push(route);
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, asyncRoutes) => {
    router.addRoutes(asyncRoutes);
    router.options.routes = constantRoutes.concat(asyncRoutes);
    state.addRoutes = asyncRoutes;
    state.routes = constantRoutes.concat(asyncRoutes);
  }
};

const actions = {
  // 生成路由
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      getMenus().then(res => {
        const menus = res.data.data.permission;
        console.log('获取个人菜单', menus);
        commit('SET_ROUTES', filterAsyncRoutes(menus));
        resolve(menus);
      });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
